// 问卷调查
import React, { useReducer, useState } from "react";
import queryApi from "../../api/query";

const ProblemContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "add_ques":
      return {
        _id: state._id,
        title: state.title,
        problem: [[...action.payload.problem0], [...action.payload.problem1]],
      };
    case "edit_ques":
      return {
        _id: state._id,
        title: state.title,
        problem: [[...action.payload.problem0], [...action.payload.problem1]],
      };
    case "get_ques":
      return {
        ...action.payload.problem,
      };
    default:
      return state;
  }
};

let initData = {
  title: "问题清单",
  problem: [[], []],
};

export const ProblemProvider = ({ children }) => {
  const [ProblemData, dispatch] = useReducer(dataReducer, initData);
  const [problemLoading, setProblemLoading] = useState("end");

  // const AddProblem = async (key, newData) => {
  //   if (key == 0) {
  //     await setProblem0([...problem0, newData]);
  //   } else if (key == 1) {
  //     await setProblem1([...problem1, newData]);
  //   }
  // // console.log("输出", problem0, problem1);
  //   await dispatch({ type: "add_ques", payload: { problem0, problem1 } });
  //   dispatch({ type: "add_ques", payload: { problem0, problem1 } });
  // // console.log("新增题目啦---", newData);
  // };

  const editProblem = (problem0, problem1) => {
    // console.log("编辑问题清单---", problem0, problem1);
    dispatch({ type: "edit_ques", payload: { problem0, problem1 } });
  };
  const postNewPro = async () => {
    try {
      let data = await queryApi.post("problem", ProblemData);
      console.log("添加问题清单模板成功---", data.data.status);
    } catch (error) {
      console.log("添加问题清单模板失败---", error);
    }
  };
  const getProblem = async () => {
    setProblemLoading("ing");
    try {
      let data = await queryApi.get("problem");
      // console.log("查找成功---", data.data.data);
      dispatch({ type: "get_ques", payload: { problem: data.data.data } });
      console.log("查找问题清单模板成功---", data.data.status);
      setProblemLoading("end");
    } catch (error) {
      console.log("查找问题清单模板失败---", error);
      setProblemLoading("error");
    }
  };
  const updataProblem = async () => {
    try {
      // console.log(ProblemData);
      await queryApi.patch("problem/" + ProblemData._id, ProblemData);
      let data = await queryApi.get("problem");
      console.log("修改问题清单模板成功---", data.data.status);
      dispatch({ type: "get_ques", payload: { problem: data.data.data } });
    } catch (error) {
      console.log("修改问题清单模板失败---", error);
    }
  };

  return (
    <ProblemContext.Provider
      value={{
        problemLoading,
        ProblemData,
        editProblem,
        postNewPro,
        getProblem,
        updataProblem,
      }}
    >
      {children}
    </ProblemContext.Provider>
  );
};

export default ProblemContext;
